/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * FichaSicologa.java
 *
 * Created on 29-10-2012, 01:13:06 AM
 */
package SubsistemaPaciente.Fichas;

import clienteSandraParada.Login;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import java.awt.Color;
import java.awt.Desktop;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Jacqueline
 */
public class FichaSicologa extends javax.swing.JDialog {

    static Long id;
    static int fila;
    String profesionall = Login.getUser().getRut();
    PanelSicologia p;

    /** Creates new form FichaSicologa */
    public FichaSicologa(java.awt.Frame parent, boolean modal, PanelSicologia p) {
        super(parent, modal);
        initComponents();
        setIconImage(new ImageIcon(getClass().getResource("/GUI/Img/logo2.png")).getImage());
        this.p = p;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel15 = new javax.swing.JPanel();
        jScrollPane6 = new javax.swing.JScrollPane();
        tablaAsistencia2 = new javax.swing.JTable();
        agregarEvolucion = new javax.swing.JButton();
        modificarEvolucion = new javax.swing.JButton();
        desdePro1 = new com.toedter.calendar.JDateChooser();
        jLabel18 = new javax.swing.JLabel();
        jLabel19 = new javax.swing.JLabel();
        hastaPro1 = new com.toedter.calendar.JDateChooser();
        verEvolucion = new javax.swing.JButton();
        jPanel13 = new javax.swing.JPanel();
        jLabel29 = new javax.swing.JLabel();
        jLabel30 = new javax.swing.JLabel();
        jLabel31 = new javax.swing.JLabel();
        nombres1 = new javax.swing.JTextField();
        apellidoPaterno1 = new javax.swing.JTextField();
        jLabel32 = new javax.swing.JLabel();
        rut = new componentes.Rut();
        apellidoMaterno1 = new javax.swing.JTextField();
        jLabel33 = new javax.swing.JLabel();
        prevision = new javax.swing.JTextField();
        jLabel34 = new javax.swing.JLabel();
        telefono = new componentes.Telefono();
        jLabel1 = new javax.swing.JLabel();
        actividad = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        celular = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        email = new javax.swing.JTextField();
        jPanel14 = new javax.swing.JPanel();
        jLabel38 = new javax.swing.JLabel();
        fechaIngreso = new com.toedter.calendar.JDateChooser();
        jLabel41 = new javax.swing.JLabel();
        jScrollPane5 = new javax.swing.JScrollPane();
        diagnostico = new javax.swing.JTextArea();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        botonCancelar = new javax.swing.JButton();
        botonAgregar = new javax.swing.JButton();
        jLabel6 = new javax.swing.JLabel();
        mensajeriaFormulario = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Ficha Psicología");
        setLocationByPlatform(true);
        setMinimumSize(new java.awt.Dimension(1106, 457));

        jPanel15.setBorder(javax.swing.BorderFactory.createTitledBorder("Atenciones realizadas"));

        tablaAsistencia2.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Sesion", "Fecha", "Evolución"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                true, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane6.setViewportView(tablaAsistencia2);

        agregarEvolucion.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/Iconos16X16/Agregar.png"))); // NOI18N
        agregarEvolucion.setToolTipText("Agregar evolución");
        agregarEvolucion.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                agregarEvolucionActionPerformed(evt);
            }
        });

        modificarEvolucion.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/Iconos16X16/Edit2.png"))); // NOI18N
        modificarEvolucion.setToolTipText("Modificar evolución");
        modificarEvolucion.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                modificarEvolucionActionPerformed(evt);
            }
        });

        desdePro1.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                desdePro1PropertyChange(evt);
            }
        });

        jLabel18.setText("Desde:");

        jLabel19.setText("Hasta:");

        hastaPro1.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                hastaPro1PropertyChange(evt);
            }
        });

        verEvolucion.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/Iconos16X16/Previsualizar.png"))); // NOI18N
        verEvolucion.setToolTipText("Ver evolución");
        verEvolucion.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                verEvolucionActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel15Layout = new javax.swing.GroupLayout(jPanel15);
        jPanel15.setLayout(jPanel15Layout);
        jPanel15Layout.setHorizontalGroup(
            jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel15Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel15Layout.createSequentialGroup()
                        .addComponent(jLabel18)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(desdePro1, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel19)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(hastaPro1, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane6, javax.swing.GroupLayout.DEFAULT_SIZE, 387, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(modificarEvolucion, 0, 0, Short.MAX_VALUE)
                        .addComponent(agregarEvolucion, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(verEvolucion, javax.swing.GroupLayout.Alignment.TRAILING, 0, 0, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel15Layout.setVerticalGroup(
            jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel15Layout.createSequentialGroup()
                .addGroup(jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel15Layout.createSequentialGroup()
                        .addGroup(jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel18)
                            .addComponent(jLabel19)
                            .addComponent(desdePro1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(hastaPro1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jScrollPane6, javax.swing.GroupLayout.DEFAULT_SIZE, 352, Short.MAX_VALUE))
                    .addGroup(jPanel15Layout.createSequentialGroup()
                        .addGap(52, 52, 52)
                        .addComponent(agregarEvolucion)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(modificarEvolucion)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(verEvolucion)
                        .addGap(0, 244, Short.MAX_VALUE)))
                .addContainerGap())
        );

        jPanel13.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos personales"));

        jLabel29.setText("Rut:");

        jLabel30.setText("Nombres:");

        jLabel31.setText("Apellido paterno:");

        nombres1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nombres1ActionPerformed(evt);
            }
        });

        jLabel32.setText("Apellido materno:");

        jLabel33.setText("Previsión:");

        jLabel34.setText("Telefono:");

        jLabel1.setText("Actividad:");

        jLabel2.setText("Celular:");

        jLabel3.setText("Email:");

        javax.swing.GroupLayout jPanel13Layout = new javax.swing.GroupLayout(jPanel13);
        jPanel13.setLayout(jPanel13Layout);
        jPanel13Layout.setHorizontalGroup(
            jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel13Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel31)
                    .addComponent(jLabel30)
                    .addComponent(jLabel29)
                    .addComponent(jLabel32)
                    .addComponent(jLabel33)
                    .addComponent(jLabel1)
                    .addComponent(jLabel3))
                .addGap(12, 12, 12)
                .addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel13Layout.createSequentialGroup()
                        .addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(nombres1, javax.swing.GroupLayout.PREFERRED_SIZE, 271, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(rut, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(jPanel13Layout.createSequentialGroup()
                                .addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(apellidoMaterno1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 284, Short.MAX_VALUE)
                                    .addComponent(apellidoPaterno1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 206, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(jPanel13Layout.createSequentialGroup()
                                        .addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                            .addComponent(actividad, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 220, Short.MAX_VALUE)
                                            .addComponent(prevision, javax.swing.GroupLayout.DEFAULT_SIZE, 220, Short.MAX_VALUE))
                                        .addGap(18, 18, 18)
                                        .addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(jLabel2)
                                            .addComponent(jLabel34))))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(celular)
                                    .addComponent(telefono, javax.swing.GroupLayout.DEFAULT_SIZE, 107, Short.MAX_VALUE))))
                        .addGap(48, 48, 48))
                    .addGroup(jPanel13Layout.createSequentialGroup()
                        .addComponent(email, javax.swing.GroupLayout.PREFERRED_SIZE, 156, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())))
        );
        jPanel13Layout.setVerticalGroup(
            jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel13Layout.createSequentialGroup()
                .addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel29)
                    .addComponent(rut, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel30)
                    .addComponent(nombres1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel13Layout.createSequentialGroup()
                        .addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel31)
                            .addComponent(apellidoPaterno1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel32)
                            .addComponent(apellidoMaterno1, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel33)
                            .addComponent(prevision, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel34)))
                    .addComponent(telefono, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(actividad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addComponent(celular, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(email, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel14.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos clínicos"));

        jLabel38.setText("Fecha ingreso:");

        jLabel41.setText("Diagnóstico:");

        diagnostico.setColumns(20);
        diagnostico.setRows(5);
        jScrollPane5.setViewportView(diagnostico);

        jLabel4.setText("*");

        jLabel5.setText("*");

        javax.swing.GroupLayout jPanel14Layout = new javax.swing.GroupLayout(jPanel14);
        jPanel14.setLayout(jPanel14Layout);
        jPanel14Layout.setHorizontalGroup(
            jPanel14Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel14Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel14Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel38)
                    .addComponent(jLabel41))
                .addGap(27, 27, 27)
                .addGroup(jPanel14Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel14Layout.createSequentialGroup()
                        .addComponent(fechaIngreso, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel14Layout.createSequentialGroup()
                        .addComponent(jScrollPane5, javax.swing.GroupLayout.PREFERRED_SIZE, 409, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jPanel14Layout.setVerticalGroup(
            jPanel14Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel14Layout.createSequentialGroup()
                .addGroup(jPanel14Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel14Layout.createSequentialGroup()
                        .addGap(6, 6, 6)
                        .addComponent(jLabel38)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel41))
                    .addGroup(jPanel14Layout.createSequentialGroup()
                        .addGroup(jPanel14Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(fechaIngreso, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel4))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel14Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel5)
                            .addComponent(jScrollPane5, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(27, Short.MAX_VALUE))
        );

        botonCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/Iconos16X16/Cancelar.png"))); // NOI18N
        botonCancelar.setText("Cancelar");
        botonCancelar.setToolTipText("Eliminar");
        botonCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonCancelarActionPerformed(evt);
            }
        });

        botonAgregar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/Iconos16X16/Agregar.png"))); // NOI18N
        botonAgregar.setText("Guardar");
        botonAgregar.setToolTipText("Guardar");
        botonAgregar.setAlignmentY(0.0F);
        botonAgregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonAgregarActionPerformed(evt);
            }
        });

        jLabel6.setText("* Datos obligatorios");

        mensajeriaFormulario.setText("Área de mensajería");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jPanel13, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jPanel14, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jPanel15, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel6)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(botonAgregar)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(botonCancelar))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(380, 380, 380)
                        .addComponent(mensajeriaFormulario, javax.swing.GroupLayout.PREFERRED_SIZE, 302, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jPanel15, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(jPanel13, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel14, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel6)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(botonCancelar)
                        .addComponent(botonAgregar)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(mensajeriaFormulario)
                .addContainerGap(28, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void nombres1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nombres1ActionPerformed
        // TODO add your handling code here:
}//GEN-LAST:event_nombres1ActionPerformed

    private void agregarEvolucionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_agregarEvolucionActionPerformed
        // agregar evoluciones
        this.mensajeriaFormulario.setText("");
        EvolucionSico evo = new EvolucionSico(null, true, this);
        evo.setTitle("Agregar Evolucion");
        evo.configurarBotones("agregar");
        evo.limpiarFormularioEvolucion();

        int sesion=calcularNumeroSesion(EvolucionSico.ficha);
        evo.agregarDatos(Integer.toString(sesion));
        evo.setLocationRelativeTo(null);
        evo.setVisible(true);
}//GEN-LAST:event_agregarEvolucionActionPerformed

    public int calcularNumeroSesion(Long ficha) {
        int numeroSesiones = 0;

        service.EvolucionWSService service = new service.EvolucionWSService();
        service.EvolucionWS port = service.getEvolucionWSPort();

        java.util.List<service.Evolucion> evoluciones = port.listarEvoluciones();
        //buscar la ficha clinica por el id de la ficha
        for (int i = 0; i < evoluciones.size(); i++) {
            if (evoluciones.get(i).getFichaClinica().equals(ficha)) {
                numeroSesiones++;
            }
        }
        if (numeroSesiones == 0) {
            return 1;
        } else {
            return numeroSesiones + 1;
        }
    }

    private void modificarEvolucionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_modificarEvolucionActionPerformed
        // modificar evolucion
        this.mensajeriaFormulario.setText("");
        EvolucionSico evo = new EvolucionSico(null, true, this);
        evo.setTitle("Modificar Evolucion");
        evo.configurarBotones("modificar");
        int[] filasSelec = tablaAsistencia2.getSelectedRows();
        if (filasSelec.length == 1) { //Devuelve -1 si no esta seleccionada
            int fil = filasSelec[0];
            service.Evolucion evoAModificar = buscarEvolucionAModificar((Integer) tablaAsistencia2.getValueAt(fil, 0),
                    (String) tablaAsistencia2.getValueAt(fil, 1), (String) tablaAsistencia2.getValueAt(fil, 2));
            EvolucionSico.idEvolucion = evoAModificar.getId();
            EvolucionSico.idFichaEvo = evoAModificar.getFichaClinica();
            evo.llenarDatosFormularioEvolucion(evoAModificar);
            evo.habilitarCamposFormulario(true);
            evo.ocultarCamposObligatorios(false);
            evo.setLocationRelativeTo(null);
            evo.setVisible(true);
        } else {
            this.mensajeriaFormulario.setText("Debe seleccionar una evolución");
            this.mensajeriaFormulario.setForeground(Color.red);
        }
}//GEN-LAST:event_modificarEvolucionActionPerformed

    public service.Evolucion buscarEvolucionAModificar(int sesion, String fecha, String comentario) {
        service.EvolucionWSService service = new service.EvolucionWSService();
        service.EvolucionWS port = service.getEvolucionWSPort();

        java.util.List<service.Evolucion> evoluciones = port.listarEvoluciones();
        //buscar la ficha clinica por el id de la ficha
        for (int i = 0; i < evoluciones.size(); i++) {
            if (evoluciones.get(i).getSesion() == sesion && evoluciones.get(i).getFecha().equals(fecha)
                    && evoluciones.get(i).getComentario().equals(comentario)) {
                return evoluciones.get(i);
            }
        }
        return null;
    }

    private void botonCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonCancelarActionPerformed
        // Cancela modificar Ficha
        this.dispose();
}//GEN-LAST:event_botonCancelarActionPerformed

    private void botonAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonAgregarActionPerformed
        //Boton formulacio agregar ficha clinica
        Long idFicha = null;
        boolean duplicada = false;

        if (this.getTitle().equals("Agregar Ficha Psicologia")) {
            duplicada = estaDuplicada(rut.getRut().getText(), Login.getUser().getRut());
            boolean datosObligatorios = llenoDatosObligatorios();
            if (duplicada == false && datosObligatorios == true) {
                idFicha = p.agregarFichaSicologaBD(rut.getRut().getText(), profesionall, capturarFecha(),
                        this.diagnostico.getText(), true);
                service.FichaSicologa f = buscarFichaSicologa(idFicha);
                String valorNuevo = "Rut profesional: " + f.getProfesional() + "\n" + "Rut paciente: " + f.getPaciente() + "\n" + "Primera consulta: " + f.getFechaPrimeraConsulta() + "\n" + "Diagnóstico: "
                        + f.getDiagnostico();
                registrar(Login.getUser(), "Ficha sicología", "Agregó ficha sicología a profesional:" + f.getProfesional() + "de paciente :" + f.getPaciente(), "No aplica", valorNuevo);
                p.cargarFichas((java.util.List<service.FichaSicologa>) listarFichas());
            } else if (duplicada == true) {
                this.mensajeriaFormulario.setText("La ficha ya se encuentra en el sistema");
                this.mensajeriaFormulario.setForeground(Color.red);
            } else if (datosObligatorios == false) {
                this.mensajeriaFormulario.setText("Complete los campos obligatorios");
                this.mensajeriaFormulario.setForeground(Color.red);
            }
            if (duplicada == false && datosObligatorios == true) {
                this.dispose();
            }
        }
        if (this.getTitle().equals("Modificar Ficha Psicologia")) {
            this.dispose();
            service.FichaSicologa f = buscarFichaSicologa(id);
           String valorAnterior = "Rut profesional: " + f.getProfesional() + "\n" + "Rut paciente: " + f.getPaciente() + "\n" + "Primera consulta: " + f.getFechaPrimeraConsulta() + "\n" + "Diagnóstico: "
        + f.getDiagnostico();
            p.modificarFichaSicologaBD(id, this.rut.getRut().getText(), profesionall, capturarFecha(), this.diagnostico.getText(), true);
            p.cargarFichas((java.util.List<service.FichaSicologa>) listarFichas());
            f = buscarFichaSicologa(id);
            String valorNuevo = "Rut profesional: " + f.getProfesional() + "\n" + "Rut paciente: " + f.getPaciente() + "\n" + "Primera consulta: " + f.getFechaPrimeraConsulta() + "\n" + "Diagnóstico: "
                    + f.getDiagnostico();
            registrar(Login.getUser(), "Ficha sicología", "Modificó ficha sicología a profesional:" + f.getProfesional() + "de paciente :" + f.getPaciente(), valorAnterior, valorNuevo);
            p.etiquetaMensajeria.setText("La Ficha se ha modificado exitosamente");
        } else if (this.getTitle().equals("Ver Ficha Psicologia")) {//Imprime la ficha Clinica
            try {
                this.dispose();
                service.FichaSicologa fichak = this.buscarFichaSicologa(id);
                imprimirFichaSicologa(fichak);
            } catch (FileNotFoundException ex) {
                Logger.getLogger(FichaSicologa.class.getName()).log(Level.SEVERE, null, ex);
            } catch (DocumentException ex) {
                Logger.getLogger(FichaSicologa.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
}//GEN-LAST:event_botonAgregarActionPerformed

    private void desdePro1PropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_desdePro1PropertyChange
        // TODO add your handling code here:
        if (this.desdePro1.getDate() != null && this.hastaPro1.getDate() != null) {
            this.actualizarTablaFiltro();
        }
    }//GEN-LAST:event_desdePro1PropertyChange

    private void hastaPro1PropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_hastaPro1PropertyChange
        // TODO add your handling code here:
        if (this.desdePro1.getDate() != null && this.hastaPro1.getDate() != null) {
            this.actualizarTablaFiltro();
        }
    }//GEN-LAST:event_hastaPro1PropertyChange

    private void verEvolucionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_verEvolucionActionPerformed
        // ver evolucion
        this.mensajeriaFormulario.setText("");
        EvolucionSico evo = new EvolucionSico(null, true, this);
        evo.setTitle("Modificar Evolucion");
        evo.configurarBotones("ver");
        int[] filasSelec = tablaAsistencia2.getSelectedRows();
        if (filasSelec.length == 1) { //Devuelve -1 si no esta seleccionada
            int fil = filasSelec[0];
            service.Evolucion evoAModificar = buscarEvolucionAModificar((Integer) tablaAsistencia2.getValueAt(fil, 0),
                    (String) tablaAsistencia2.getValueAt(fil, 1), (String) tablaAsistencia2.getValueAt(fil, 2));
            EvolucionSico.idEvolucion = evoAModificar.getId();
            EvolucionSico.idFichaEvo = evoAModificar.getFichaClinica();
            evo.llenarDatosFormularioEvolucion(evoAModificar);
            evo.habilitarCamposFormulario(false);
            evo.ocultarCamposObligatorios(true);
            evo.setLocationRelativeTo(null);
            evo.setVisible(true);
        } else {
            this.mensajeriaFormulario.setText("Debe seleccionar una evolución");
            this.mensajeriaFormulario.setForeground(Color.red);
        }        
    }//GEN-LAST:event_verEvolucionActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField actividad;
    private javax.swing.JButton agregarEvolucion;
    private javax.swing.JTextField apellidoMaterno1;
    private javax.swing.JTextField apellidoPaterno1;
    public javax.swing.JButton botonAgregar;
    public javax.swing.JButton botonCancelar;
    private javax.swing.JTextField celular;
    private com.toedter.calendar.JDateChooser desdePro1;
    private javax.swing.JTextArea diagnostico;
    private javax.swing.JTextField email;
    private com.toedter.calendar.JDateChooser fechaIngreso;
    private com.toedter.calendar.JDateChooser hastaPro1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel18;
    private javax.swing.JLabel jLabel19;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel29;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel30;
    private javax.swing.JLabel jLabel31;
    private javax.swing.JLabel jLabel32;
    private javax.swing.JLabel jLabel33;
    private javax.swing.JLabel jLabel34;
    private javax.swing.JLabel jLabel38;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel41;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel13;
    private javax.swing.JPanel jPanel14;
    private javax.swing.JPanel jPanel15;
    private javax.swing.JScrollPane jScrollPane5;
    private javax.swing.JScrollPane jScrollPane6;
    public javax.swing.JLabel mensajeriaFormulario;
    private javax.swing.JButton modificarEvolucion;
    private javax.swing.JTextField nombres1;
    private javax.swing.JTextField prevision;
    private componentes.Rut rut;
    private javax.swing.JTable tablaAsistencia2;
    private componentes.Telefono telefono;
    private javax.swing.JButton verEvolucion;
    // End of variables declaration//GEN-END:variables

    public String capturarFecha() {
        Calendar cal = Calendar.getInstance();
        String fecha = "dd-MM-yyyy";
        if (this.fechaIngreso.getDate() != null) {
            cal.setTime(this.fechaIngreso.getDate());
            //Dia - mes - año
            fecha = Integer.toString(cal.get(Calendar.DAY_OF_MONTH)) + "-"
                    + Integer.toString(cal.get(Calendar.MONTH) + 1) + "-"
                    + Integer.toString(cal.get(Calendar.YEAR));
        }
        return fecha;
    }

    public Date stringToDate(String strFecha) {
        SimpleDateFormat formatoDelTexto = new SimpleDateFormat("dd-MM-yyyy");
        Date fecha = null;
        try {
            fecha = formatoDelTexto.parse(strFecha);
        } catch (ParseException ex) {
            ex.printStackTrace();
        }
        return fecha;
    }

    public void limpiarFormularioSico() {
        //datos personales
        this.rut.getRut().setText("");
        this.nombres1.setText("");
        this.apellidoPaterno1.setText("");
        this.apellidoMaterno1.setText("");
        this.prevision.setText("");
        this.telefono.getTelefono().setText("");
        this.actividad.setText("");
        this.celular.setText("");
        this.email.setText("");
        //datos clinicos
        this.fechaIngreso.setDate(null);
        this.diagnostico.setText(null);
    }

    void llenarFormulario(service.FichaSicologa ficha) {
        //buscar información del paciente seleccionado
        service.Paciente pac = new service.Paciente();
        pac = buscarPaciente(ficha.getPaciente());
        //llenar datos paciente
        this.rut.getRut().setText(ficha.getPaciente());
        this.nombres1.setText(pac.getNombres());
        this.apellidoPaterno1.setText(pac.getApellidoPaterno());
        this.apellidoMaterno1.setText(pac.getApellidoMaterno());
        this.prevision.setText(pac.getPrevision());
        this.telefono.getTelefono().setText(pac.getTelefono());
        this.actividad.setText(pac.getProfesion());
        this.celular.setText(pac.getCelular());
        this.email.setText(pac.getEmail());
        //bloquear los campos
        this.rut.getRut().setEditable(false);
        this.nombres1.setEditable(false);
        this.apellidoPaterno1.setEditable(false);
        this.apellidoMaterno1.setEditable(false);
        this.prevision.setEditable(false);
        this.telefono.getTelefono().setEditable(false);
        this.actividad.setEditable(false);
        this.celular.setEditable(false);
        this.email.setEditable(false);
        //llena los datos clinicos del paciente
        if (!ficha.getFechaPrimeraConsulta().equals("dd-MM-yyyy")) {
            this.fechaIngreso.setDate(stringToDate(ficha.getFechaPrimeraConsulta()));
        }
        this.diagnostico.setText(ficha.getDiagnostico());
    }

    public void llenarFormularioAgregar(service.Paciente pac) {
        //llenar datos paciente
        this.rut.getRut().setText(pac.getRut());
        this.nombres1.setText(pac.getNombres());
        this.apellidoPaterno1.setText(pac.getApellidoPaterno());
        this.apellidoMaterno1.setText(pac.getApellidoMaterno());
        this.prevision.setText(pac.getPrevision());
        this.telefono.getTelefono().setText(pac.getTelefono());
        this.actividad.setText(pac.getProfesion());
        this.celular.setText(pac.getCelular());
        this.email.setText(pac.getEmail());
        //bloquear los campos
        this.rut.getRut().setEditable(false);
        this.nombres1.setEditable(false);
        this.apellidoPaterno1.setEditable(false);
        this.apellidoMaterno1.setEditable(false);
        this.prevision.setEditable(false);
        this.telefono.getTelefono().setEditable(false);
        this.actividad.setEditable(false);
        this.celular.setEditable(false);
        this.email.setEditable(false);
        //bloquear campos de evoluciones
        this.agregarEvolucion.setEnabled(false);
        this.modificarEvolucion.setEnabled(false);
        this.desdePro1.setEnabled(false);
        this.hastaPro1.setEnabled(false);
        this.verEvolucion.setEnabled(false);
    }

    public service.Paciente buscarPaciente(String paciente) {
        service.PacienteWS_Service service = new service.PacienteWS_Service();
        service.PacienteWS port = service.getPacienteWSPort();

        java.util.List<service.Paciente> pacientes = port.listarPacientes();
        //buscar paciente por el rut
        for (int i = 0; i < pacientes.size(); i++) {
            if (pacientes.get(i).getRut().equals(paciente)) {
                return pacientes.get(i);
            }
        }
        return null;
    }

    void habilitarCamposFormularioSico(boolean habilitar) {
        this.fechaIngreso.setEnabled(habilitar);
        this.diagnostico.setEditable(habilitar);
        //habilitar datos evoluciones
        this.agregarEvolucion.setEnabled(habilitar);
        this.modificarEvolucion.setEnabled(habilitar);
        this.desdePro1.setEnabled(habilitar);
        this.hastaPro1.setEnabled(habilitar);
        this.verEvolucion.setEnabled(habilitar);
    }

    public void configurarBotones(String formulario) {
        if (formulario.equals("agregar")) {
            this.botonAgregar.setText("Aceptar");
            this.botonAgregar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/Iconos16X16/Agregar.png")));
        } else if (formulario.equals("modificar")) {
            this.botonAgregar.setText("Guardar");
            this.botonAgregar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/Iconos16X16/Agregar.png")));
        } else {
            this.botonAgregar.setText("Exportar");
            this.botonAgregar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/Iconos16X16/pdf.png")));
        }
    }

    private boolean estaDuplicada(String paciente, String profesional) {
        java.util.List<service.FichaSicologa> fichas = listarFichas();
        for (int i = 0; i < fichas.size(); i++) {
            if (fichas.get(i).getPaciente().equals(paciente) && fichas.get(i).getProfesional().equals(profesional)) {
                return true;
            }
        }
        return false;
    }

    private static java.util.List<service.FichaSicologa> listarFichas() {
        service.FichaSicologaWSService service = new service.FichaSicologaWSService();
        service.FichaSicologaWS port = service.getFichaSicologaWSPort();
        return port.listarFichasSicologa();
    }

    public service.FichaSicologa buscarFichaSicologa(Long fichaSico) {
        service.FichaSicologaWSService service = new service.FichaSicologaWSService();
        service.FichaSicologaWS port = service.getFichaSicologaWSPort();

        java.util.List<service.FichaSicologa> fichasSicologa = port.listarFichasSicologa();
        //buscar paciente por el rut
        for (int i = 0; i < fichasSicologa.size(); i++) {
            if (fichasSicologa.get(i).getId().equals(fichaSico)) {
                return fichasSicologa.get(i);
            }
        }
        return null;
    }

    public String eligeDireccionArchivo() {
        String dirArchivo = "";
        JFileChooser jFileChooser1 = new JFileChooser();
        jFileChooser1.setDialogTitle("Guardar archivo:");
        jFileChooser1.setVisible(true);

        int r = jFileChooser1.showSaveDialog(null);
        if (r == JFileChooser.APPROVE_OPTION) {
            File file = jFileChooser1.getSelectedFile();
            dirArchivo = String.valueOf(file);
        }
        dirArchivo = dirArchivo.replace('\\', '/') + ".pdf";
        return dirArchivo;

    }

    private void imprimirFichaSicologa(service.FichaSicologa ficha) throws FileNotFoundException, DocumentException {
        service.Paciente paciente = buscarPaciente(ficha.getPaciente());
        Document documento = new Document();
        String dirArchivo = eligeDireccionArchivo();

        FileOutputStream ficheroPdf = new FileOutputStream(dirArchivo);// Se crea el OutputStream para el fichero donde queremos dejar el pdf.
        // Se asocia el documento al OutputStream y se indica que el espaciado entre
        // lineas sera de 20. Esta llamada debe hacerse antes de abrir el documento
        PdfWriter.getInstance(documento, ficheroPdf).setInitialLeading(20);
        documento.open();// Se abre el documento.

        Paragraph titulo = new Paragraph("FICHA CLINICA PSICOLOGÍA");
        titulo.setAlignment(Element.ALIGN_CENTER);
        titulo.setSpacingAfter(20);
        documento.add(titulo);

        Paragraph datosPersonales = new Paragraph("Datos Personales");
        datosPersonales.setAlignment(Element.ALIGN_LEFT);
        datosPersonales.setSpacingAfter(20);
        documento.add(datosPersonales);

        PdfPTable table = new PdfPTable(2);
        table.addCell("Rut: ");
        table.addCell(paciente.getRut());
        table.addCell("Nombres: ");
        table.addCell(paciente.getNombres());
        table.addCell("Apellido Paterno:");
        table.addCell(paciente.getApellidoPaterno());
        table.addCell("Apellido Materno: ");
        table.addCell(paciente.getApellidoMaterno());
        table.addCell("Previsión: ");
        table.addCell(paciente.getPrevision());
        table.addCell("Actividad: ");
        table.addCell(paciente.getProfesion());
        table.addCell("Telefono: ");
        table.addCell(paciente.getTelefono());
        table.addCell("Celular: ");
        table.addCell(paciente.getCelular());
        table.addCell("Email: ");
        table.addCell(paciente.getEmail());
        documento.add(table);

        Paragraph datosClinicos = new Paragraph("Datos Clínicos");
        datosClinicos.setAlignment(Element.ALIGN_LEFT);
        datosClinicos.setSpacingAfter(20);
        documento.add(datosClinicos);

        PdfPTable tabla = new PdfPTable(2);
        tabla.addCell("Fecha Primera Consulta: ");
        tabla.addCell(ficha.getFechaPrimeraConsulta());
        tabla.addCell("Profesional: ");
        tabla.addCell(ficha.getProfesional());
        tabla.addCell("Diagnóstico: ");
        tabla.addCell(ficha.getDiagnostico());
        documento.add(tabla);

        documento.close();
        abrirArchivo(dirArchivo);
    }

    public void abrirArchivo(String direccion) {
        //Abre el documento pdf
        try {
            File file = new File(direccion);
            Desktop.getDesktop().open(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void agregarDatoTablaEvolucion(int sesion, String fechaEvolucion, String comentario) {
        int fila = this.tablaAsistencia2.getRowCount();
        DefaultTableModel modelo = (DefaultTableModel) this.tablaAsistencia2.getModel();
        modelo.addRow(new String[3]);

        //coloca los datos de la ficha recientemente agregada
        for (int col = 0; col < this.tablaAsistencia2.getColumnCount(); col++) {
            this.tablaAsistencia2.setValueAt(sesion, fila, 0);
            this.tablaAsistencia2.setValueAt(fechaEvolucion, fila, 1);
            this.tablaAsistencia2.setValueAt(comentario, fila, 2);
        }
    }

    public void llenardatosEvoluciones(Long id) {
        //listar Evoluciones y agregarlas a la Tabla
        service.EvolucionWSService service = new service.EvolucionWSService();
        service.EvolucionWS port = service.getEvolucionWSPort();
        //Obtiene las fichas clinicas almacenadas en la base de datos
        java.util.List<service.Evolucion> evoluciones = port.listarEvoluciones();
        for (int i = 0; i < evoluciones.size(); i++) {
            if (evoluciones.get(i).isActivo() == true && evoluciones.get(i).getFichaClinica().equals(id)) {

                int fila = this.tablaAsistencia2.getRowCount();
                DefaultTableModel modelo = (DefaultTableModel) this.tablaAsistencia2.getModel();
                modelo.addRow(new String[3]);

                for (int col = 0; col < this.tablaAsistencia2.getColumnCount(); col++) {
                    this.tablaAsistencia2.setValueAt(evoluciones.get(i).getSesion(), fila, 0);
                    this.tablaAsistencia2.setValueAt(evoluciones.get(i).getFecha(), fila, 1);
                    this.tablaAsistencia2.setValueAt(evoluciones.get(i).getComentario(), fila, 2);
                }
            }
        }
    }

    public void limpiarTablaEvoluciones() {
        DefaultTableModel modelo = (DefaultTableModel) tablaAsistencia2.getModel();
        int filas = tablaAsistencia2.getRowCount();
        for (int i = 0; filas > i; i++) {
            modelo.removeRow(0);
        }
    }

    public void cambiarMensajeria(String eti) {
        p.etiquetaMensajeria.setText(eti);
    }

    public void modificarDatoTabla(int s, String fecha, String comentario) {
        int fila = this.tablaAsistencia2.getSelectedRow();
        this.tablaAsistencia2.setValueAt(s, fila, 0);
        this.tablaAsistencia2.setValueAt(fecha, fila, 1);
        this.tablaAsistencia2.setValueAt(comentario, fila, 2);
    }

    private boolean llenoDatosObligatorios() {
        if (this.fechaIngreso.getDate() == null || this.diagnostico.getText().equals("")) {
            return false;
        }
        return true;
    }

    private void actualizarTablaFiltro() {
        this.limpiarTablaEvoluciones();
        //listar Evoluciones y agregarlas a la Tabla
        service.EvolucionWSService service = new service.EvolucionWSService();
        service.EvolucionWS port = service.getEvolucionWSPort();
        //Obtiene las fichas clinicas almacenadas en la base de datos
        java.util.List<service.Evolucion> evoluciones = port.listarEvoluciones();

        for (int i = 0; i < evoluciones.size(); i++) {
            Date d = this.stringToDate(evoluciones.get(i).getFecha());
            if (evoluciones.get(i).isActivo() == true && evoluciones.get(i).getFichaClinica().equals(id)) {
                if (this.desdePro1.getDate().before(d) && this.hastaPro1.getDate().after(d) || this.esMismoDia(this.desdePro1.getDate(), d)
                        || this.esMismoDia(this.hastaPro1.getDate(), d)) {

                    int fila = this.tablaAsistencia2.getRowCount();
                    DefaultTableModel modelo = (DefaultTableModel) this.tablaAsistencia2.getModel();
                    modelo.addRow(new String[3]);
                    for (int col = 0; col < this.tablaAsistencia2.getColumnCount(); col++) {
                        this.tablaAsistencia2.setValueAt(evoluciones.get(i).getSesion(), fila, 0);
                        this.tablaAsistencia2.setValueAt(evoluciones.get(i).getFecha(), fila, 1);
                        this.tablaAsistencia2.setValueAt(evoluciones.get(i).getComentario(), fila, 2);
                    }
                }
            }
        }
    }

    private static boolean esMismoDia(Date fecha1, Date fecha2) {
        if (fecha1 == null || fecha2 == null) {
            throw new IllegalArgumentException("Las fechas no pueden ser null");
        }
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(fecha1);
        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(fecha2);
        return isSameDay(cal1, cal2);
    }

    private static boolean isSameDay(Calendar cal1, Calendar cal2) {
        if (cal1 == null || cal2 == null) {
            throw new IllegalArgumentException("Las fechas no pueden ser null");
        }
        return (cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) && cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) && cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR));
    }

    private static Long registrar(service.Usuario usuario, java.lang.String modulo, java.lang.String accion, java.lang.String valorAnterior, java.lang.String valorNuevo) {
        service.BitacoraWSService service = new service.BitacoraWSService();
        service.BitacoraWS port = service.getBitacoraWSPort();
        return port.registrar(usuario, modulo, accion, valorAnterior, valorNuevo);
    }
    
    public void ocultarAsteriscosFormulario(boolean ocultar){
        if(ocultar==true){
            this.jLabel4.setText("");
            this.jLabel5.setText("");
            this.jLabel6.setText("");
            this.mensajeriaFormulario.setText("");
        }else{
            this.jLabel4.setText("*");
            this.jLabel5.setText("*");
            this.jLabel6.setText("*Datos obligatorios");
            this.mensajeriaFormulario.setText("Área de mensajería");
        }
    }
    
    void habilitarCamposEvolucion(boolean b) {
        this.desdePro1.setEnabled(b);
        this.hastaPro1.setEnabled(b);
        this.tablaAsistencia2.setEnabled(b);
        this.verEvolucion.setEnabled(b);
    }
}
